#!/usr/bin/env bash

# This file is part of bashy2, an irc bot used on irc.sdf.org.

# Copyright (C) 2015-2016 mlaine@sdfeu.org, grugly@sdf.org
# Copyright (C) 2017-2018 mlaine@sdfeu.org

# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:

# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#-----------------------------------------------------------------------

## Options 0 = on, 1 = off, logfile = file
debug=1

source './bits/conf.sh'
source './bits/vitalbits.sh'
source './bits/nonvitalbits.sh'

function init {
    exec 3<&-
    exec 3<>"/dev/tcp/$irc_host/$irc_port" || return 1
    send 'user' "$bot_user" "$bot_real"
    send 'nick' "$bot_nick"
    declare -g quiet=1
}

function main {
    init
    while true; do
        ## the -t is the read timer, and needs to account for the server ping setting
        if IFS=$' \t\r' read -ru3 -a data -t 140; then
            debug 'IN:' "${data[@]}"
            if [[ "${data[0]}" = 'PING' ]]; then
                send 'pong' "${data[1]}"
                continue
            fi
            case "${data[1]}" in
                'PRIVMSG')
                    priv "${data[@]}" ;;
                'JOIN')
                    user_join "${data[@]}" ;;
                'QUIT')
                    user_quit "${data[@]}" ;;
                '001')
                    send 'oper' "$bot_user" "$(awk 'NR==1' "$irc_pass")"
                    serv 'join' ;;
                '332'|'331')
                    chtopic "${data[@]}" ;;
                '352'|'315')
                    upall "${data[@]}" ;;
                '311'|'319')
                    up "${data[@]}" ;;
            esac
        else
            ## If we get here, it's cause bashy needs to restart/connect
            sleep 300
            init
        fi
    done
}

main

